package cn.ibizlab.util.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class SSOAuthenticationEntryPoint implements org.springframework.security.web.AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -8970718410437077606L;

    @Autowired
    AuthenticationEntryPoint authenticationEntryPoint;
    public static final String ssoUri = "/login";

    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        String requestURI = request.getRequestURI();
        if (!ObjectUtils.isEmpty(requestURI) && requestURI.startsWith("/oauth")) {
            String uri = String.format("%1$s?redirect=%2$s",ssoUri,URLEncoder.encode(buildRequestUri(request), "UTF-8"));
            new LoginUrlAuthenticationEntryPoint(uri).commence(request, response, authException);
        } else {
            authenticationEntryPoint.commence(request, response, authException);
        }
    }

    /**
     * 从HttpServletRequest中获取请求的URL和参数，拼接成完整的URI。
     *
     * @param request HttpServletRequest对象
     * @return 拼接后的URI字符串
     */
    protected String buildRequestUri(HttpServletRequest request) {
        // 获取请求的URL
        StringBuilder url = new StringBuilder(request.getRequestURL().toString());

        // 获取请求的查询参数
        Map<String, String[]> parameterMap = request.getParameterMap();

        if (!parameterMap.isEmpty()) {
            url.append("?");

            // 将参数转换成查询字符串并拼接到URL后面
            String queryString = parameterMap.entrySet().stream()
                    .map(entry -> entry.getKey() + "=" + String.join(",", entry.getValue()))
                    .collect(Collectors.joining("&"));

            url.append(queryString);
        }

        return url.toString();
    }
}
